// 处理参数格式
function setQuerry(params) {
    let strArr = []
    for (let key in params) {
        let str = key + '=' + params[key]
        strArr.push(str)
    }
    strArr.join('&')
}

//封装ajax请求
const myAjax = function(option){
    const p = new Promise((resolve, reject) => {
        // 创建xhr
        const xhr = new XMLHttpRequest()
       // 传参
       const querry = setQuerry(option.data)
       //判断请求类型
       if(option.method.toUpperCase() === 'GET'){
        xhr.open('GET', option.data ? option.url + '?' + querry : option.url)
        xhr.send()
       } else if(option.method.toUpperCase() === 'POST'){
        xhr.open('POST',option.url)
        // 设置请求头
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
        xhr.send(querry)
       }
       // 监听
       xhr.onreadystatechange = function() {
         if(xhr.readyState === 4) {
            if(xhr.status === 200) {
                resolve (JSON.parse(xhr.responseText))
            } else {
                reject('404 NOT FOUND!')
            }
         }
        }
    })

    return p
}